package com.bgamq.atcrowd.service.impl;

import com.bgamq.atcrowd.constant.CrowdConstant;
import com.bgamq.atcrowd.entity.Admin;
import com.bgamq.atcrowd.entity.AdminExample;
import com.bgamq.atcrowd.exception.LoginAcctAlreadyInUseException;
import com.bgamq.atcrowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.bgamq.atcrowd.exception.LoginFailedException;
import com.bgamq.atcrowd.mapper.AdminMapper;
import com.bgamq.atcrowd.service.api.AdminService;
import com.bgamq.atcrowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @author admin
 */
@Service
public class AdminServiceImpl implements AdminService {


    private final AdminMapper adminMapper;

    private final BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public AdminServiceImpl(AdminMapper adminMapper, BCryptPasswordEncoder passwordEncoder) {
        this.adminMapper = adminMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void saveAdmin(Admin admin) {

        String pswd = admin.getUserPswd();
        String adminPswd = passwordEncoder.encode(pswd);
//        String adminPswd = CrowdUtil.md5(pswd);
        admin.setUserPswd(adminPswd);

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        String format = formatter.format(date);
        admin.setCreateTime(format);

        try {
            adminMapper.insert(admin);
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof DuplicateKeyException){
                throw  new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(null);
    }

    @Override
    public Admin getAdminByLoginAcct(String acct, String pswd) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(acct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        if(adminList == null || adminList.size() == 0){
            throw new  LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        if(adminList.size()>1){
            throw  new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        Admin admin = adminList.get(0);
        if(admin == null){
            throw new  LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        String adminUserPswd = admin.getUserPswd();

        String md5 = CrowdUtil.md5(pswd);

        if(!Objects.equals(adminUserPswd,md5)){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);

        List<Admin> admins = adminMapper.selectAdminByKeyword(keyword);

        return new PageInfo<>(admins);
    }

    @Override
    public void remove(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Admin getAdminById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        }catch (Exception  e){
            e.printStackTrace();
            if(e instanceof DuplicateKeyException){
                throw  new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 1.根据 adminId 删除旧的关联关系数据
        adminMapper.deleteOLdRelationship(adminId);
        // 2.根据 roleIdList 和 adminId 保存新的关联关系
        if(roleIdList != null && roleIdList.size() > 0) {
            adminMapper.insertNewRelationship(adminId, roleIdList);
        }
    }

    @Override
    public Admin getAdminByLoginAcct(String username) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(username);

        List<Admin> admins = adminMapper.selectByExample(adminExample);
        Admin admin = admins.get(0);

        return admin;
    }
}
